package com.fa.wisdom.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.coder.zzq.smartshow.dialog.LoadingDialog;
import com.fa.wisdom.R;
import com.fa.wisdom.adapter.CatgoodsAdapter;
import com.fa.wisdom.adapter.MenuAdapter;
import com.fa.wisdom.base.BaseFragment;
import com.fa.wisdom.model.CategoryEntity;
import com.fa.wisdom.model.CatgoodsEntity;
import com.fa.wisdom.model.ResultEntity;
import com.fa.wisdom.net.MyCallback;
import com.fa.wisdom.net.Task;
import com.fa.wisdom.ui.GoodsFDetailActivity;
import com.fa.wisdom.ui.LoginActivity;
import com.fa.wisdom.utils.Loading;
import com.fa.wisdom.utils.ScreenUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Response;

public class ShopFragment extends BaseFragment {

    private static final String TAG = "CAT";

    View statusBarPlace;
    ImageView titleLeft;
    TextView titleMid;

    //列表
    ListView lvMenu;
    MenuAdapter menuAdapter;
    List<CategoryEntity> menuList = new ArrayList<>();
    String currentCatId = "";//当前选中的分类ID
    String categoryId = "";//首页跳转过来的分类ID（优先判断）

    //商品
    ImageView ivLogo;
    TextView tvMenutitle;
    RecyclerView rvGoods;
    CatgoodsAdapter catgoodsAdapter;
    List<CatgoodsEntity> catgoodsList = new ArrayList<>();
    LoadingDialog loadingDialog;

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_shop, null);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        statusBarPlace = view.findViewById(R.id.view_status_bar_place);
        titleLeft = view.findViewById(R.id.title_left);
        titleMid = view.findViewById(R.id.title_mid);
        lvMenu = view.findViewById(R.id.lv_menu);
        ivLogo = view.findViewById(R.id.iv_logo);
        tvMenutitle = view.findViewById(R.id.tv_menutitle);
        rvGoods = view.findViewById(R.id.rv_goods);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        titleLeft.setVisibility(View.GONE);
        titleMid.setText("分类");

        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (getArguments() != null) {
                categoryId = getArguments().getString("categoryId");
                getArguments().putString("categoryId", "");
            }
            if (loadingDialog == null)
                loadingDialog = Loading.getInstance().onShowLargeLoading( "加载中...");
            initData();
        }
    }

    /**
     * 初始化界面
     */
    private void initView() {

        //分类
        menuAdapter = new MenuAdapter(getActivity(), menuList);
        lvMenu.setAdapter(menuAdapter);
        lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                currentCatId = menuList.get(i).getCategoryId();//当前选中位置的分类ID
                menuAdapter.setSelectColor(i);
                menuAdapter.notifyDataSetChanged();
                //更改商品信息
                getCatGoods(menuList.get(i).getCategoryId());
            }
        });
        //商品数据
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        rvGoods.setLayoutManager(gridLayoutManager);
        catgoodsAdapter = new CatgoodsAdapter(getActivity(), catgoodsList);
        rvGoods.setAdapter(catgoodsAdapter);
        catgoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (ScreenUtil.isFastClick()) {
                    return;
                }
                //todo 跳转到商品详情
                String goodId=catgoodsList.get(position).getGoodsId();
                startActivity(new Intent(requireActivity(), GoodsFDetailActivity.class)
                .putExtra("goodId",goodId));
            }
        });

    }

    /**
     * 加载数据
     */
    private void initData() {
        loadingDialog.showInActivity(requireActivity());
        Task.getApiService().getCate().enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response<ResultEntity> response) {
                try {
                    String jsonString = JSON.toJSONString(response.body());
                    JSONObject jsonObject = JSON.parseObject(jsonString);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    List<CategoryEntity> catList = new ArrayList<>();
                    if (jsonArray != null && jsonArray.size() > 0) {
                        catList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            CategoryEntity categoryEntity = new CategoryEntity();
                            categoryEntity.setCategoryId(String.valueOf(jsonObject1.getInteger("id")));
                            categoryEntity.setCategoryIcon("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.dabaoku.com%2Fsucai%2Fzhiwulei%2Fshucai%2F0024.jpg&refer=http%3A%2F%2Fwww.dabaoku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628657306&t=178e712f49044cddce33345ad4505e56");
                            categoryEntity.setCategoryTitle(jsonObject1.getString("name"));
                            catList.add(categoryEntity);
                        }
                    }
                    if (catList.size() > 0) {
                        menuList.clear();
                        menuList.addAll(catList);
                        menuAdapter.notifyDataSetChanged();

                        //显示商品
                        if (!menuList.isEmpty()) {
                            if (TextUtils.isEmpty(categoryId)) {//非跳转
                                if (TextUtils.isEmpty(currentCatId)) {//如果没有选中项，默认选择第一项
                                    //更改商品信息
                                    menuAdapter.setSelectColor(0);
                                    menuAdapter.notifyDataSetChanged();
                                    getCatGoods(menuList.get(0).getCategoryId());
                                } else {//如果有选中项，这显示选择项
                                    boolean isHas = true;
                                    for (int i = 0; i < menuList.size(); i++) {
                                        if (currentCatId.equals(menuList.get(i).getCategoryId())) {
                                            isHas = false;
                                            //更改商品信息
                                            menuAdapter.setSelectColor(i);
                                            menuAdapter.notifyDataSetChanged();
                                            getCatGoods(menuList.get(i).getCategoryId());
                                            break;
                                        }
                                    }
                                    if (isHas) {
                                        menuAdapter.setSelectColor(0);
                                        menuAdapter.notifyDataSetChanged();
                                        getCatGoods(menuList.get(0).getCategoryId());
                                    }
                                }
                            } else {//显示指定项
                                currentCatId = categoryId;//选定项为跳转的分类
                                for (int i = 0; i < menuList.size(); i++) {
                                    if (menuList.get(i).getCategoryId().equals(categoryId)) {
                                        menuAdapter.setSelectColor(i);
                                        menuAdapter.notifyDataSetChanged();
                                        getCatGoods(menuList.get(i).getCategoryId());
                                        categoryId = "";
                                        break;
                                    }
                                }
                                if (!TextUtils.isEmpty(categoryId)) {//没找到，默认显示选中项
                                    if (TextUtils.isEmpty(currentCatId)) {//当前选中项为空，这显示第一项
                                        menuAdapter.setSelectColor(0);
                                        menuAdapter.notifyDataSetChanged();
                                        getCatGoods(menuList.get(0).getCategoryId());
                                    } else {//如果有选中项，这显示选择项
                                        boolean isHas = true;
                                        for (int i = 0; i < menuList.size(); i++) {
                                            if (currentCatId.equals(menuList.get(i).getCategoryId())) {
                                                isHas = false;
                                                //更改商品信息
                                                menuAdapter.setSelectColor(i);
                                                menuAdapter.notifyDataSetChanged();
                                                getCatGoods(menuList.get(i).getCategoryId());
                                                break;
                                            }
                                        }
                                        if (isHas) {
                                            menuAdapter.setSelectColor(0);
                                            menuAdapter.notifyDataSetChanged();
                                            getCatGoods(menuList.get(0).getCategoryId());
                                        }
                                    }
                                    categoryId = "";
                                }
                            }
                        } else {//商品为空，跳转过来的分类ID置空
                            categoryId = "";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loadingDialog.dismiss();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 获取选中分类的商品
     */
    private void getCatGoods(String catId) {
        if (!loadingDialog.isShowing())
            loadingDialog.showInActivity(requireActivity());
        Task.getApiService().getGoods(1, 10, Integer.parseInt(catId)).enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response<ResultEntity> response) {
                try {
                    loadingDialog.dismiss();
                    String jsonString = JSON.toJSONString(response.body());
                    JSONObject jsonObject = JSON.parseObject(jsonString);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    List<CatgoodsEntity> goodsList = new ArrayList<>();
                    if (jsonArray != null && jsonArray.size() > 0) {
                        goodsList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            CatgoodsEntity catgoodsEntity = new CatgoodsEntity();
                            catgoodsEntity.setGoodsId(String.valueOf(jsonObject1.getInteger("id")));
                            catgoodsEntity.setGoodsTitle(jsonObject1.getString("goodsname"));
                            catgoodsEntity.setPreviewImage(jsonObject1.getJSONArray("get_image").getJSONObject(0).getString("image"));
                            goodsList.add(catgoodsEntity);
                        }
                    }
                    catgoodsList.clear();
                    catgoodsList.addAll(goodsList);
                    catgoodsAdapter.setNewData(catgoodsList);
                } catch (Exception e) {
                    e.printStackTrace();
                    loadingDialog.dismiss();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                loadingDialog.dismiss();
            }
        });
    }
}
